import React from 'react';
import { Row, Col, Modal, Input, message, Tooltip } from 'antd';
import Zcon from '@cbd/icon';
import { getUuid } from 'utils/comm';
import styles from './index.less';

const { TextArea } = Input;
const DELETE = Symbol('DELETE')
export default class ParametersEditor extends React.Component {
  constructor(props) {
    super(props);
    const { selectData: httpcallbackData = {} } = props;
    const { parameters = [] } = httpcallbackData;
    this.state = {
      edittingIndex:-1,
      httpcallbackData: {
        ...httpcallbackData,
        parameters: parameters.map(item => ({
          ...item,
          id: getUuid(),
        })),
      },
    }
    this.previousKeyValue = null;
    this.newEdit = false;
    this.edittingKeyInputRef = React.createRef();
  }

  componentDidUpdate() {
    if (this.newEdit) {
      this.focus();
      this.newEdit = false;
    }
  }

  focus = () => {
    if (this.edittingKeyInputRef.current) {
      this.edittingKeyInputRef.current.focus();
    }
  }

  /*      -----     编辑key value 相关方法 start     -----      */
  onAdd = () => {
    const { edittingIndex, httpcallbackData = {} } = this.state;
    if (edittingIndex > -1) {
      message.warn("请先完成当前编辑");
      this.focus();
      return;
    }
    const { parameters = [] } = httpcallbackData;
    // const newIndex = parameters.length;
    const newData = {
      ...httpcallbackData,
      parameters: [
        { id: getUuid(), key:'', value: '' },
        ...parameters,
      ],
    };
    this.previousKeyValue = DELETE;
    this.newEdit = true;
    this.setState({
      // edittingIndex: newIndex,
      edittingIndex: 0,
      httpcallbackData: newData,
    });
  }

  onCancel = () => {
    const {
      edittingIndex,
      httpcallbackData,
    } = this.state;
    const { parameters } = httpcallbackData;
    const newValue = [ ...parameters ];

    if (this.previousKeyValue === DELETE) {
      newValue.splice(edittingIndex, 1);
    } else {
      newValue.splice(edittingIndex, 1, this.previousKeyValue);
    }
    const newData = {
      ...httpcallbackData,
      parameters: newValue,
    };
    this.previousKeyValue = null;
    this.setState({
      edittingIndex: -1,
      httpcallbackData: newData,
    });
  }

  onDelete = (index) => {
    const { httpcallbackData = {} } = this.state;
    const { parameters = [] } = httpcallbackData;
    if (parameters.length > index) {
      parameters.splice(index, 1);
      this.setState({
        httpcallbackData: {
          ...httpcallbackData,
          parameters,
        },
      });
    }
  }

  onChange = (index, key, value) => {
    const { httpcallbackData = {} } = this.state;
    const { parameters = [] } = httpcallbackData;
    const item = parameters[index] || {};
    item[key] = value;
    parameters[index] = item;
    this.setState({
      httpcallbackData: {
        ...httpcallbackData,
        parameters,
      },
    });
  }

  onConfirm = (index) => {
    const { httpcallbackData = {} } = this.state;
    const { parameters = [] } = httpcallbackData;
    const item = parameters[index] || {};
    if (!item.key || !item.key.trim()) {
      message.warn("KEY 值不能为空");
      this.focus();
      return;
    }
    this.setState({ edittingIndex: -1 });
    this.previousKeyValue = null;
  }

  onEdit = (index) => {
    const { httpcallbackData = {} } = this.state;
    const { parameters = [] } = httpcallbackData;
    const item = parameters[index];
    if (item) {
      this.previousKeyValue = { ...item };
      this.newEdit = true;
      this.setState({ edittingIndex: index });
    }
  }
  /*      -----     编辑key value 相关方法 end     -----      */

  handleCancel = () => {
    const { onCancel } = this.props;
    if (typeof onCancel === 'function') {
      onCancel();
    }
  }

  handleOk = () => {
    const { formSelect } = this.props;
    const { edittingIndex, httpcallbackData = {} } = this.state;
    if (edittingIndex > -1) {
      message.warn("请先完成当前编辑");
      this.focus();
      return;
    }
    if (typeof formSelect === 'function') {
      formSelect(httpcallbackData);
    }
  }

  render() {
    const { edittingIndex, httpcallbackData } = this.state;
    const { visible, className } = this.props;
    const _className = `${styles.root} ${className}`;
    const { parameters = [] } = httpcallbackData;
    return (
      <Modal
        title={(
          <div className={styles.title}>
            <span>HTTP请求回调</span>
            <Tooltip
              overlayClassName={styles.tooltip}
              title={(
                <div style={{lineHeight: "20px"}}>
                  HTTP请求设置，包括URL以及参数设置，
                  流程变量以#开头，例如user=#loginUserId
                </div>
              )}
            >
              <span className={styles.ques}>?</span>
            </Tooltip>
          </div>
        )}
        visible={visible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
        // wrapClassName={styles.wrap}
        width={528}
        okText="确定"
        cancelText="取消"
        maskClosable={false}
      >
        <Row
          className={_className}
        >
          <Row type="flex" className={styles.cols_2}>
            <Col className={styles.col1} style={{paddingTop: 5}}>
              请输入URL：
            </Col>
            <Col className={styles.col2}>
              <TextArea
                onChange={e => {
                  const { httpcallbackData: data = {} } = this.state;
                  data.url = e.target.value;
                  this.setState({
                    httpcallbackData: { ...data },
                  });
                }} 
                placeholder="请输入URL"
                value={httpcallbackData.url}
              />
            </Col>
          </Row>
          <Row
            align="middle"
            justify="end"
            style={{marginTop: 24}}
            type="flex"
          >
            <div
              className={styles.add}
              onClick={this.onAdd}
            >
              <Zcon type="plus" />
              <span>添加参数</span>
            </div>
          </Row>
          <Row type="flex" className={`${styles.cols_2} ${styles.borderFix}`}>
            <Col className={styles.col1} style={{lineHeight: '40px'}}>
              参数列表:
            </Col>
            <Col className={styles.col2}>
              <Row
                className={`${styles.formTitle} ${styles.borderRow}`}
                type="flex"
                align="middle"
              >
                <div>KEY</div>
                <div>VALUE</div>
                <div>操作</div>
              </Row>
              {parameters.map((item, index) => {
                const props = {
                  edittingIndex,
                  index,
                  item,
                  key: item.id,
                  onCancel: this.onCancel,
                  onChange: this.onChange,
                  onConfirm: this.onConfirm,
                  onDelete: this.onDelete,
                  onEdit: this.onEdit,
                  ...(edittingIndex === index ?
                    {ref: this.edittingKeyInputRef} : {}
                  ),
                };
                return <KeyValueItem {...props} />
              })}
              { parameters.length === 0 ?
                <div className={`${styles.placeHolder} ${styles.borderRow}`}>暂无数据</div> : null
              }
            </Col>
          </Row>
        </Row>
      </Modal>
    );
  }
}

const KeyValueItem = React.forwardRef(
  ({
    edittingIndex,
    index,
    item,
    onCancel,
    onChange,
    onConfirm,
    onDelete,
    onEdit,
  }, ref) => {
    const {
      key = '',
      value ='',
    } = item;
    const isEditting = edittingIndex === index;
    const disabled = edittingIndex > -1;
    const valueInputRef = React.createRef();
    if (isEditting) {
      return (
        <Row
          className={styles.borderRow}
          type="flex"
          align="middle"
        >
          <div>
            <Input
              onChange={(e) => onChange(index, 'key', e.target.value)}
              onPressEnter={(e) => {
                const val = e.target.value;
                if (val && val.trim()) {
                  if (valueInputRef.current) {
                    valueInputRef.current.focus();
                  }
                }
              }}
              placeholder="请输入key"
              ref={ref}
              value={key}
            />
          </div>
          <div>
            <Input
              onChange={(e) => onChange(index, 'value', e.target.value)}
              onPressEnter={(e) => {
                const val = e.target.value;
                if (val && val.trim()) {
                  onConfirm(index);
                }
              }}
              placeholder="请输入value"
              ref={valueInputRef}
              value={value}
            />
          </div>
          <div className={styles.opera}>
            <span onClick={() => onConfirm(index)}>确定</span>
            <span onClick={() => onCancel(index)}>取消</span>
          </div>
        </Row>
      );
    } else {
      return (
        <Row
          className={styles.borderRow}
          type="flex"
          align="middle"
        >
          <div className={styles.keyValueLabel} title={key}>{key}</div>
          <div className={styles.keyValueLabel} title={value}>{value}</div>
          <div className={`${styles.opera} ${disabled ? styles.disabled : ''}`}>
            <span onClick={() => !disabled && onEdit(index)}>编辑</span>
            <span onClick={() => !disabled && onDelete(index)}>删除</span>
          </div>
        </Row>
      );
    }
  }
)
